package servlet;

import bean.User;
import dao.UserDao;
import dao.UserInfoDao;
import net.sf.json.JSONObject;
import util.JsonWrapper;
import util.ResponseUtil;
import util.TokenUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 骑行用户登陆
 *
 * @author 邓晴予
 */
public class UserLoginServlet extends HttpServlet {
    private UserDao userDao = new UserDao();
    private UserInfoDao userInfoDao = new UserInfoDao();

    /**
     * @author 邓晴予
     * 骑行用户登陆
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

//		获取用户名密码
        String phone = req.getParameter("phone");
        String password = req.getParameter("password");
        User user = new User();
        user.setPhone(phone);
        user.setPassword(password);
        User resultUser = null;
        JsonWrapper result = new JsonWrapper();

        try {
            resultUser = userDao.login(user);
            if (resultUser != null) {
                result.setStatus(200);
                result.setMsg("success");
                JSONObject info = new JSONObject();
                info.put("userId", resultUser.getUserId());
                info.put("userName", resultUser.getUserName());
                info.put("name", resultUser.getName());
                info.put("phone", resultUser.getPhone());
                info.put("card", resultUser.getCardNumber());
                info.put("balance", resultUser.getBalance());
                info.put("score", resultUser.getScore());
                info.put("status", resultUser.getStatus());
                info.put("userInfoId", resultUser.getUserInfoId());
                info.put("audit", userInfoDao.isAudit(resultUser.getUserId()));
                result.setDataEntry("jwt", TokenUtil.generateJWT(phone));
                result.setDataJsonObject("user", info);
            } else {
//				查询正确，骑行用户信息验证失败
                result.setStatus(402);
                result.setMsg("failed");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setStatus(401);
            result.setMsg("failed");
        }

        ResponseUtil.write(resp, result);
    }
}
